package jdbc;

import cn.itcast.dao.DaoException;
import utils.JdbcUtils;

import java.lang.reflect.Method;
import java.sql.*;

public class ORMDemo {

    public static Object read(Class clazz) throws Exception {
        // 初始化
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "SELECT * FROM  USER WHERE id=1";


        try {
            conn = JdbcUtils.getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            Object obj = null;

            while (rs.next()) {
                obj = clazz.newInstance();
                for (int i=1; i<=columnCount; i++) {
                    String columnName = rsmd.getColumnName(i);

                    String methodName = "set" + columnName.toUpperCase();
                    Method method = clazz.getMethod(methodName);
                    method.invoke(obj, rs.getObject(rsmd.getColumnClassName(i)));
                }
            }
            return obj;
        } catch (SQLException e) {
            throw new DaoException(e);
        } finally {
            JdbcUtils.free(ps, conn, null);
        }

    }

}
